package kr.pe.johnkim.pushchat.mobile.controller;

import kr.pe.johnkim.pushchat.mobile.domain.PushChatMember;
import kr.pe.johnkim.pushchat.mobile.util.PushChatCommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * 모바일 서비스를 사용하는 다른 모듈에게 Push Notification 기능을 제공하는 클래스이다.
 * (예 : 웹사이트에서 가맹점이 이벤트를 등록하면 아래의 메소드를 호출해서 방문했던 사용자들에게 Push Notification 을 송신한다.)
 *
 * @author : John_Kim <cale9797@gmail.com>
 * @date : 13. 7. 2.
 */
@Controller
@RequestMapping(value = "/pushChatNotificationController")
public class PushChatNotificationController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(PushChatNotificationController.class);

    @Autowired
    private PushChatCommon pushChatCommon;

    /**
     * Android 사용자에게 Push Notification 을 보낸다.
     *
     * @param pushChatMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pushNotificationToAndroid", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatMember pushNotificationToAndroid(@RequestBody PushChatMember pushChatMember) throws Exception {
        logger.info("pushNotificationToAndroid");

        PushChatMember result = new PushChatMember();

        try {
            pushChatCommon.sendASMessage(pushChatMember.getRegistrationId(), pushChatMember.getMessageContent());
            result.setResult("SUCCESS");
            logger.info("success to send push notification to android smart phone.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to send push notification to android smart phone.");
        }

        return result;
    }

    /**
     * iOS 사용자에게 Push Notification 을 보낸다.
     * 테스트용이며 운영계에 적용하기 전에 sendIPMessage() 로 수정할 것.
     *
     * @param pushChatMember
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/pushNotificationToiOS", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatMember pushNotificationToiOS(@RequestBody PushChatMember pushChatMember) throws Exception {
        logger.info("pushNotificationToiOS");

        PushChatMember result = new PushChatMember();

        try {
            pushChatCommon.testSendIPMessage(pushChatMember.getRegistrationId(), pushChatMember.getMessageContent(), "", "");
            result.setResult("SUCCESS");
            logger.info("success to send notification to iOS smart phone.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to send notification to iOS smart phone.");
        }

        return result;
    }
}
